package com.minelx.datamicroscope.querylanguage.data.sql;

import com.alibaba.druid.sql.ast.statement.SQLExprTableSource;
import com.alibaba.druid.sql.ast.statement.SQLJoinTableSource;
import com.alibaba.druid.sql.ast.statement.SQLTableSource;
import com.minelx.sequence.core.StringScanner;

public final class CommonTable {

	private final String databaseIndex;

	private final String databaseName;

	private final String tableName;

	public CommonTable(String databaseIndex, String databaseName, String tableName) {
		this.databaseIndex = databaseIndex;
		this.databaseName = databaseName;
		this.tableName = tableName;
	}

	public String fieldLocatePath(String fieldName) {
		return path() + "." + fieldName;
	}

	public String path() {
		return this.databaseIndex + "@" + this.databaseName + "@" + this.tableName;
	}

	public static CommonTable from(String text) {
		String[] joinedTablePattern = text.split("@");
		return new CommonTable(joinedTablePattern[0], joinedTablePattern[1], joinedTablePattern[2]);
	}

	public static CommonTable from(SQLTableSource fromTable) {
		if (fromTable instanceof SQLExprTableSource) {
			String content = fromTable.toString();
			return from(content.substring(1, content.length() - 1));
		} else if (fromTable instanceof SQLJoinTableSource) {
			// join table expr
			StringScanner source = StringScanner.source(fromTable.toString());
			source.goes("`");
			return from(source.til('`'));
		} else {
			throw new UnsupportedOperationException("FromTableExpr.create is not implemented yet.");
		}
	}
}
